//
//  StorageManager.swift
//  ZZBase
//
//  Created by 张文晏 on 2018/9/25.
//  Copyright © 2018 张文晏. All rights reserved.
//  存储

import Foundation

/// 存储管理器
open class StorageManager {
    // MARK: - Variables
    /// 单例
    public static let shared = StorageManager()
    /// 存储记忆
    public let behavioralMemory = BehavioralMemory()
    
    /// 文件夹路径
    private static let directoryPath = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .allDomainsMask, true).first ?? "") + "/StorageManager"
    
    private init() {
        var isDir = ObjCBool(true)
        if !FileManager.default.fileExists(atPath: StorageManager.directoryPath, isDirectory: &isDir) {
            do {
                try FileManager.default.createDirectory(atPath: StorageManager.directoryPath, withIntermediateDirectories: false, attributes: nil)
            } catch {
                print(error.localizedDescription)
            }
        }
    }
    
    
    /// 行为记忆
    open class BehavioralMemory {
        /// 文件路径
        private let filePath = directoryPath + "/BehavioralMemory"
        /// 存储字典
        private var infoDic = [String: Any]()
        
        init() {
            if !FileManager.default.fileExists(atPath: filePath) {
                FileManager.default.createFile(atPath: filePath, contents: nil, attributes: nil)
            }
            if
                let data = FileManager.default.contents(atPath: filePath),
                let dic = (try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)) as? [String: Any] {
                infoDic = dic
            } else {
                print("error")
            }
        }
        
        /// 存储
        open func set(value: Any?, key: String) { infoDic[key] = value }
        
        /// 读取
        open func get(key: String) -> Any? { return infoDic[key] }
        
        /// 保存
        open func save() {
            if !FileManager.default.fileExists(atPath: filePath) {
                FileManager.default.createFile(atPath: filePath, contents: nil, attributes: nil)
            }
            do {
                let data = try JSONSerialization.data(withJSONObject: infoDic, options: .init(rawValue: 0))
                try data.write(to: URL(fileURLWithPath: filePath), options: .atomic)
            } catch {
                print(error.localizedDescription)
            }
        }
        
        /// 清理
        open func clean() {
            infoDic.removeAll()
            do {
                try FileManager.default.removeItem(atPath: filePath)
            } catch {
                print(error.localizedDescription)
            }
        }
    }
}
